<template>
  <div>
    <h2>执行排产算法</h2>
    
    <!-- 排产配置表单 -->
    <el-card class="config-card">
      <template #header>
        <h3>排产配置</h3>
      </template>
      
      <el-form 
        ref="scheduleFormRef"
        :model="scheduleForm" 
        :rules="scheduleRules"
        label-width="140px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input 
                v-model="scheduleForm.planName" 
                placeholder="请输入排产计划名称"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排产算法" prop="algorithmType">
              <el-select 
                v-model="scheduleForm.algorithmType" 
                placeholder="请选择排产算法"
                style="width: 100%"
              >
                <el-option
                  v-for="algorithm in availableAlgorithms"
                  :key="algorithm"
                  :label="getAlgorithmDisplayName(algorithm)"
                  :value="algorithm"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排产起始时间" prop="scheduleStartTime">
              <el-date-picker
                v-model="scheduleForm.scheduleStartTime"
                type="datetime"
                placeholder="选择排产起始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="createdBy">
              <el-input 
                v-model="scheduleForm.createdBy" 
                placeholder="请输入创建人"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注信息">
          <el-input 
            v-model="scheduleForm.remark" 
            type="textarea" 
            placeholder="请输入备注信息"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 待排产工单选择 -->
    <el-card class="orders-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <h3>选择待排产订单</h3>
          <el-button type="primary" @click="loadPendingOrders" :loading="loadingOrders">
            刷新订单列表
          </el-button>
        </div>
      </template>
      
      <div class="orders-table-container">
        <el-table 
          ref="orderTableRef"
          :data="pendingOrders" 
          @selection-change="handleSelectionChange"
          style="width: 100%" 
          v-loading="loadingOrders"
          border
          height="400"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="orderId" label="订单ID" width="150" sortable />
          <el-table-column prop="customerName" label="客户名称" width="150" sortable />
          <el-table-column prop="customerContact" label="客户联系方式" width="150" show-overflow-tooltip sortable />
          <el-table-column prop="dueDate" label="交货日期" width="120" sortable />
          <el-table-column prop="totalQuantity" label="总数量" width="100" sortable />
          <el-table-column prop="status" label="状态" width="100" sortable>
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="completionRate" label="完成率" width="100" sortable>
            <template #default="scope">
              {{ (scope.row.completionRate * 100).toFixed(1) }}%
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="140" sortable />
          <el-table-column label="订单项" min-width="200">
            <template #default="scope">
              <div v-for="item in scope.row.orderItems" :key="item.orderItemId" style="margin-bottom: 5px;">
                <el-tag size="small" style="margin-right: 5px;">{{ item.productName }}</el-tag>
                <span style="font-size: 12px; color: #666;">数量: {{ item.quantity }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        type="primary" 
        size="large"
        @click="executeSchedule"
        :loading="executing"
        :disabled="selectedOrders.length === 0"
      >
        执行排产算法
      </el-button>
      <el-button 
        size="large"
        @click="resetForm"
      >
        重置
      </el-button>

    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const API_BASE_URL = 'http://117.72.45.141:8091';

// 定义事件发射器
const emit = defineEmits(['plan-saved']);

// 响应式数据
const scheduleFormRef = ref(null);
const orderTableRef = ref(null);
const pendingOrders = ref([]);
const selectedOrders = ref([]);
const availableAlgorithms = ref([]);
const loadingOrders = ref(false);
const executing = ref(false);
const router = useRouter();

// 算法名称中英文映射
const algorithmNameMap = {
  'PRODUCT_BATCH': '同种产品集中生产算法', 
  'MACHINE_UTILIZATION': '负载均衡算法',
  'ENHANCED_GENETIC_ALGORITHM': '增强遗传算法',
  'DEFAULT_FIFO': 'FIFO默认排序算法',
  'CRITICAL_PATH_SPT': '关键路径SPT算法',
  "COMBINE_ALGORITHM": '紧急优先与机器利用率结合算法'
  
};

// 获取算法中文名称
const getAlgorithmDisplayName = (englishName) => {
  return algorithmNameMap[englishName] || englishName;
};

// 排产表单数据
const scheduleForm = reactive({
  planName: '',
  algorithmType: '',
  orderIds: [],
  scheduleStartTime: '',
  createdBy: '',
  remark: ''
});

// 表单验证规则
const scheduleRules = {
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
    { min: 1, max: 100, message: '计划名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  algorithmType: [
    { required: true, message: '请选择排产算法', trigger: 'change' }
  ],
  createdBy: [
    { required: true, message: '请输入创建人', trigger: 'blur' }
  ]
};

// 加载支持的排产算法
const loadAlgorithms = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/schedule/algorithms`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      availableAlgorithms.value = response.data.data || [];
    } else {
      ElMessage.error('获取排产算法列表失败');
    }
  } catch (error) {
    console.error('获取排产算法失败:', error);
    ElMessage.error('获取排产算法失败');
  }
};

// 加载待排产订单
const loadPendingOrders = async () => {
  loadingOrders.value = true;
  try {
    const response = await axios.get(`${API_BASE_URL}/api/orders/pending`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      pendingOrders.value = response.data.data || [];
      ElMessage.success(`加载了 ${pendingOrders.value.length} 个待排产订单`);
    } else {
      ElMessage.error('获取待排产订单失败');
    }
  } catch (error) {
    console.error('获取待排产订单失败:', error);
    ElMessage.error('获取待排产订单失败');
  } finally {
    loadingOrders.value = false;
  }
};

// 处理订单选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection;
  scheduleForm.orderIds = selection.map(order => order.orderId);
};

// 执行排产算法
const executeSchedule = async () => {
  if (!scheduleFormRef.value) return;
  
  try {
    const valid = await scheduleFormRef.value.validate();
    if (!valid) return;
  } catch (error) {
    return;
  }
  
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择至少一个待排产订单');
    return;
  }
  
  executing.value = true;
  try {
    // 确保创建人信息正确设置
    if (!scheduleForm.createdBy) {
      scheduleForm.createdBy = localStorage.getItem('username') || '系统用户';
    }
    
    console.log('执行排产算法，请求数据:', scheduleForm);
    
    const response = await axios.post(`${API_BASE_URL}/api/schedule/execute`, scheduleForm, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    console.log('排产执行响应:', response.data);
    
    if (response.data.code === 200) {
      const scheduleResult = response.data.data;
      console.log('排产结果数据:', scheduleResult);
      
      // 保存数据到sessionStorage并跳转到结果页面
      const resultData = {
        scheduleResult: scheduleResult,
        planData: {
          planName: scheduleForm.planName,
          algorithmType: scheduleForm.algorithmType
        },
        orderIds: selectedOrders.value.map(order => order.orderId) // 保存订单ID以便保存计划时使用
      };
      
      sessionStorage.setItem('scheduleResult', JSON.stringify(resultData));
      
      ElMessage.success('排产算法执行完成，正在跳转到结果页面...');
      
      // 跳转到排产结果页面
      router.push('/schedule-result');
    } else {
      console.error('排产执行失败:', response.data);
      ElMessage.error(response.data.message || '排产执行失败');
    }
  } catch (error) {
    console.error('执行排产算法失败:', error);
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('排产执行失败，请检查网络连接');
    }
  } finally {
    executing.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (scheduleFormRef.value) {
    scheduleFormRef.value.resetFields();
  }
  Object.assign(scheduleForm, {
    planName: '',
    algorithmType: '',
    orderIds: [],
    scheduleStartTime: '',
    createdBy: '',
    remark: ''
  });
  selectedOrders.value = [];
  if (orderTableRef.value) {
    orderTableRef.value.clearSelection();
  }
};

// 设置选中的订单（供父组件调用）
const setSelectedOrders = (orderIds) => {
  // 根据订单ID选中对应的行
  if (orderTableRef.value && pendingOrders.value.length > 0) {
    const ordersToSelect = pendingOrders.value.filter(order => 
      orderIds.includes(order.orderId)
    );
    ordersToSelect.forEach(order => {
      orderTableRef.value.toggleRowSelection(order, true);
    });
  }
};



// 状态标签类型
const getStatusTagType = (status) => {
  const types = {
    '待排产': 'info',      // 灰色
    '已排产': 'primary',   // 蓝色
    '生产中': 'danger',    // 红色
    '生产完成': 'success'  // 绿色
  };
  return types[status] || 'default';
};

onMounted(() => {
  loadAlgorithms();
  loadPendingOrders();
  
  // 设置默认值
  scheduleForm.scheduleStartTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
  scheduleForm.createdBy = localStorage.getItem('username') || '系统用户';
});

// 暴露方法给父组件
defineExpose({
  setSelectedOrders
});
</script>

<style scoped>
.config-card, .orders-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #409eff;
  font-weight: 600;
}

.orders-table-container {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  overflow: hidden;
}

.action-buttons {
  text-align: center;
  margin-top: 30px;
  position: sticky;
  bottom: 20px;
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.action-buttons .el-button {
  margin: 0 10px;
}

h3 {
  margin: 20px 0 10px 0;
  color: #409eff;
  font-weight: 600;
}
</style> 